package cn.zf233.xcloud.config.common;

import cn.zf233.xcloud.service.core.MemoryCoordinate;
import cn.zf233.xcloud.service.core.PersistenceService;
import cn.zf233.xcloud.util.OSSUtil;
import cn.zf233.xcloud.util.RedisUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by zf233 on 2021/1/14
 * XCloud 文件上传核心服务配置类
 */
@Configuration
public class PersistenceServiceConfig {

    private static final int CONSUMER_SIZE = 10;
    private static final int MAX_TASK_SIZE_OF_CONSUMER = 10;
    private static final String THREAD_NAME_PREFIX = "Async-Upload-";

    @Resource
    private MemoryCoordinate memory;

    @Resource
    private PersistenceService.IFailFileRemove fileService;

    @Bean
    public PersistenceService persistenceService(OSSUtil ossUtil, RedisUtil redisUtil) {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(CONSUMER_SIZE);
        threadPool.setMaxPoolSize(CONSUMER_SIZE);
        threadPool.setKeepAliveSeconds(0);
        threadPool.setQueueCapacity(0);
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        threadPool.setThreadNamePrefix(THREAD_NAME_PREFIX);
        threadPool.initialize();
        PersistenceService persistenceService = new PersistenceService(CONSUMER_SIZE, memory, fileService);
        persistenceService.setMaxTaskSizeOfConsumer(MAX_TASK_SIZE_OF_CONSUMER);
        persistenceService.setThreadPool(threadPool);
        persistenceService.setOssUtil(ossUtil);
        persistenceService.setRedisUtil(redisUtil);
        persistenceService.init();
        return persistenceService;
    }
}